package com.zelin.reference;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * TCP协议
 * 客户端
 */
public class TcpClient {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Socket socket = null;
        OutputStream outputStream = null;
        ObjectOutputStream oos = null;
        InputStream inputStream = null;
        try {
            //创建客户端，连接到指定的服务端  ip 和 端口号
            socket = new Socket("127.0.0.1", 6666);
            System.out.println("连接到服务端");

            //录入用户对象信息
            System.out.print("请输入用户名：");
            String name = input.next();
            System.out.print("请输入密码：");
            String password = input.next();
            User user = new User(name, password);

            //发送消息到服务端
            outputStream = socket.getOutputStream();
            oos = new ObjectOutputStream(outputStream);
            //序列化对象
            oos.writeObject(user);

            //读取服务端的消息
            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int length = inputStream.read(b); //等待对方输出消息
            String info = new String(b, 0, length);
            System.out.println("服务端：" + info);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert inputStream != null;
                inputStream.close();
                oos.flush();
                oos.close();
                outputStream.flush();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
